import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleBIOHttpServer {
    public static void main(String[] args) {
        int port = 8081;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                run(serverSocket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void run(ServerSocket serverSocket) throws IOException {
        Socket clientSocket = serverSocket.accept();
        System.out.println("Accepted connection from " + clientSocket.getRemoteSocketAddress());

        // 创建一个线程来处理客户端请求
        try (
                InputStream inputStream = clientSocket.getInputStream();
                OutputStream outputStream = clientSocket.getOutputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream))
        ) {
            // 读取HTTP请求
            String line;
            StringBuilder request = new StringBuilder();
            while ((line = reader.readLine()) != null && !line.isEmpty()) {
                request.append(line).append("\r\n");
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 处理HTTP请求，这里可以编写你的业务逻辑
            String httpResponse = "HTTP/1.1 200 OK\r\n\r\nHello, World!\r\n";
            writer.write(httpResponse);
            writer.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
